﻿using System.Collections.ObjectModel;
using Caliburn.Micro;
using Serialization;
using Wulong.Phone.Dianping.Models;

namespace Wulong.Phone.Dianping.ViewModels
{
    public class MerchantsByChannelViewModelStorage : 
        StorageHandler<MerchantsByChannelViewModel>
    {
        public override void Configure()
        {
            AddInstruction().Configure(x =>
            {
                x.Key = "merchantsByChannel";

                x.Save = (instance, getKey, mode) =>
                {
                    var value = SilverlightSerializer.Serialize(instance._merchants);
                    x.StorageMechanism.Store(getKey(), value);
                };
                x.Restore = (instance, getKey, mode) =>
                {
                    object value;
                    var key = getKey();

                    if (x.StorageMechanism.TryGet(key, out value))
                    {
                        instance._merchants = (value == null)
                                                    ? null
                                                    : SilverlightSerializer.
                                                          Deserialize(
                                                              (byte[])value) as ObservableCollection<Merchant>;

                        x.StorageMechanism.Delete(key);
                    }

                };
            }).InPhoneState().RestoreAfterViewReady();
        }
    }
}
